import { Form, Input, Button, RadioGroup, Radio, Checkbox } from "tea-component";
import React from "react";
import { Form as FinalForm, Field } from "react-final-form";
import { getStatus } from "../../../../utils/getStatus";
import { GroupTypeSelect } from "./GroupTypeSelect";

import "./create-group-form.scss";
import useAsyncRetryFunc from "../../../../utils/react-use/useAsyncRetryFunc";
import { getFriendList } from "../../../../api";
import { Avatar } from "../../../../components/avatar/avatar";
import Toast from "../../../../components/toast/Toast";

const validateOldValue = async (value: string, label: string) => {
  if (!value) {
    return `${label}必填`;
  }
};

export interface FormValue {
  groupName: string;
  groupAnnouncement: string;
  joinGroupMode: string;
  groupMember: string[];
  groupType: string;
}

interface CreateGroupFormProps {
  onSubmit: (formValue: FormValue) => Promise<void>;
  onSuccess?: () => void;
  onError?: () => void;
  onClose?: () => void;
  data?: any
}

export const CreateGroupForm = (props: CreateGroupFormProps): JSX.Element => {
  const { onSubmit, onSuccess, onError, onClose } = props;
  const { value, loading, retry } = useAsyncRetryFunc(async () => {
    return await getFriendList();
  }, []);
  const friendList = value || [];

  // eslint-disable-next-line
  const _handlerSubmit = async (formValue: FormValue) => {
    try {
      await onSubmit(formValue);
      onSuccess?.();
    } catch (error) {
      onError?.();
    }
  };
  const gtype =  Toast.serConfig?.group_type=="Public"?"0":"5";
  return (
    <FinalForm onSubmit={_handlerSubmit} initialValuesEqual={() => true} initialValues={{  groupType: gtype,  joinGroupMode: "2",}}>
      {({ handleSubmit, submitting, validating, values }) => {
        const { groupType } = values;
        return (
          <form onSubmit={handleSubmit}>
            <Form layout="fixed" style={{ width: "100%" }}>
              <Field name="groupName"  disabled={submitting}  validateOnBlur validateFields={[]}
                validate={(value) => validateOldValue(value, "群聊名称")} >
                {({ input, meta }) => (
                  <Form.Item  required  label="群聊名称" status={getStatus(meta, validating)}
                    message={
                      getStatus(meta, validating) === "error" && meta.error
                    }>
                    <Input  {...input} placeholder="请输入" size="full"  disabled={submitting} />
                  </Form.Item>
                )}
              </Field>
              <Field  name="groupType"  disabled={submitting} validateOnBlur  validateFields={[]}
                validate={(value) => validateOldValue(value, "群类型")} >
                {({ input, meta }) => (
                  <Form.Item  required  label="群类型"  status={getStatus(meta, validating)}
                    message={
                      getStatus(meta, validating) === "error" && meta.error
                    } >
                    <GroupTypeSelect  {...input}  type="simulate"  size="full"  appearance="button"  disabled={false}
                    />
                  </Form.Item>
                )}
              </Field>
              <Field name="groupMember"  disabled={submitting}  validateOnBlur  validateFields={[]}
                validate={(value) => validateOldValue(value, "群成员")}>
                {({ input, meta }) => (
                  <Form.Item required label="群成员" status={getStatus(meta, validating)}
                    message={ getStatus(meta, validating) === "error" && meta.error}>
                      <div style={{maxHeight:"200px",display:"flex",overflowY:"scroll"}}>
                        <Checkbox.Group  {...input}  layout="column">
                          {friendList.map( (item:any) =>{
                            const profile = {
                                userId: item.friend_profile_user_profile.user_profile_identifier,
                                nickName: item.friend_profile_remark||item.friend_profile_user_profile.user_profile_nick_name,
                                faceUrl: item.friend_profile_user_profile.user_profile_face_url,
                                gender: item.friend_profile_user_profile.user_profile_gender,
                                role: item.friend_profile_user_profile.user_profile_role,
                            }
                            //console.log(profile);
                            return(
                            <Checkbox name={item.friend_profile_identifier} >
                               <Avatar  url={profile.faceUrl}  nickName={profile.nickName}   userID={profile.userId}/>
                              <div><span className="item-left__info--name">{profile.nickName || profile.userId}</span></div>
                            </Checkbox>
                            ) 
                          })}
                        </Checkbox.Group>
                        </div>
                  </Form.Item>
                ) }
              </Field>
            </Form>
            <Form.Action>
              <Button className="btn" type="primary" htmlType="submit" loading={submitting} >
                添加
              </Button>
              <Button className="btn" loading={submitting} onClick={(e) => {
                  e.stopPropagation(); e.preventDefault();
                  onClose();
                }}>
                取消
              </Button>
            </Form.Action>
          </form>
        );
      }}
    </FinalForm>
  );
};
